#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 读取二进制数据到可变缓冲区中
问题: 你想直接读取二进制数据到一个可变缓冲区中，而不需要做任何的中间复制操作。 或者你想原地修改数据并将它写回到一个文件中去。
提示 : 
"""

import os.path

def recipe1():
    # Write a sample file
    filename1 = '09_read_tobuffer_1.bin'
    with open(filename1, 'wb') as f:
        f.write(b'Hello World')

    buf = read_into_buffer(filename1)
    print(f"{buf = }")


    with open('09_read_tobuffer_2.bin', 'wb') as f:
        f.write(buf)

    # 缓冲区执行切片操作
    m1 = memoryview(buf)
    m2 = m1[-5:]
    print(f"{m2 = }")
    m2[:] = b'WORLD'
    print(f"{buf = }")

def read_into_buffer(filename):
    '''读取数据到一个可变数组中'''
    buf = bytearray(os.path.getsize(filename))
    with open(filename, 'rb') as f:
        f.readinto(buf)
    return buf

def read_into_buffer1(filename):
    record_size = 32
    buf = bytearray(record_size)
    with open(filename, 'rb') as f:
        while True:
            n = f.readinto(buf)
            if n < record_size:
                break
            # Use the contents of buf

def main():
    print('recipe1'.center(20, '*'))
    recipe1()

if __name__ == '__main__':
    main()                    
